package org.soenea.doitall.domain.model.person.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.soenea.doitall.domain.model.person.IPerson;
import org.soenea.doitall.domain.model.person.Person;
import org.soenea.doitall.domain.model.person.PersonProxy;
import org.soenea.doitall.domain.model.person.data.PersonFinder;
import org.soenea.doitall.domain.model.person.data.PersonTDG;

public class PersonInputMapper {
	public static List<Person> findAll() throws MapperException {
		List<Person> people = new Vector<Person>();
		try {
			ResultSet rs = PersonFinder.findAll();
			while (rs.next()) {
				people.add(getPerson(rs));
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
		return people;
	}

	public static Person find(long id) throws MapperException,
			DomainObjectNotFoundException {
		try {
			ResultSet rs = PersonFinder.find(id);
			if (rs.next()) {
				return getPerson(rs);
			} else {
				throw new DomainObjectNotFoundException("Person " + id);
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
	}
	
	public static List<Person> findAllWithoutGroup(long id) throws MapperException {
		List<Person> people = new Vector<Person>();
	try {
		ResultSet rs = PersonFinder.findAllWithoutGroup(id);
		while (rs.next()) {
			people.add(getPerson(rs));
		}
	} catch (SQLException e) {
		throw new MapperException(e);
	}
	return people;
}
	
	public static Person find(String userName, String password) throws MapperException,
	DomainObjectNotFoundException {
try {
	ResultSet rs = PersonFinder.findByName(userName, password);
	if (rs.next()) {
		return getPerson(rs);
	} else {
		throw new DomainObjectNotFoundException("This username/password combination is not found.");
	}
} catch (SQLException e) {
	throw new MapperException(e);
}
}

	private static Person getPerson(ResultSet rs) throws SQLException {
		Person result = new Person(rs.getLong("p.userId"),rs.getString("p.userName"),rs.getString("p.password"),rs.getInt("p.groupNum"), 
				rs.getString("p.firstName"),rs.getString("p.lastName"),rs.getLong("p.version"));
		return result;
	}
}
